package com.qysoft.rapid.actions.mybatis;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.NumberFormats;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.qysoft.rapid.actions.JsonResultInterceptor;
import com.qysoft.rapid.actions.RapidAction;
import com.qysoft.rapid.consts.RapidConsts;
import com.qysoft.rapid.core.RapidDbConn;
import com.qysoft.rapid.dao.mybatis.RapidDao;
import com.qysoft.rapid.dao.mybatis.common.CommonDao;
import com.qysoft.rapid.domain.CurrentRyxx;
import com.qysoft.rapid.exceptions.RapidException;
import com.qysoft.rapid.utils.DateUtil;

/**
 * ibatis控制层封装
 * @author liugong
 *
 */
@Before(JsonResultInterceptor.class)
public abstract class BaseCommonAction extends RapidAction {
	
	/**
	 * 注入参数处理
	 * @param parameters
	 */
	public abstract void handlerPar(HashMap<String, Object> parameters) throws Exception;
	
	/**
	 * 导出excel、cell字段
	 * @param value
	 * @return
	 */
	public abstract String rendererCellData(String sqlid,String dataIndex,String value) throws Exception;
	
	/**
	 * 分页查询
	 * @throws Exception
	 */
	@Before(RapidDbConn.class)
	public void extQuery() throws Exception{
		HashMap<String, Object> parameters = (HashMap<String, Object>) this.getParams();
		handlerPar(parameters);
		int page = getParaToInt("page");
		int limit = getParaToInt("limit");
		String sqlid = getPara("sqlid");
		if (sqlid==null) {
			throw new RapidException("未设置sqlid！");
		}
		Page<HashMap<String, Object>> result = CommonDao.paginateByXml(page,limit,"Dynasearch_"+sqlid+"_count", "Dynasearch_"+sqlid+"_getData", parameters);
		setJson(result);
	}	
	
	/**
	 * 公用查询 返回多条数据
	 */
	public void commonQuery() throws Exception {
		HashMap<String, Object> parameters = (HashMap<String, Object>) this.getParams();
		handlerPar(parameters);
		String sqlid = getPara("sqlid");
		if (sqlid==null) {
			throw new RapidException("未设置sqlid！");
		}
		List<Object> result = CommonDao.selectListByXml(sqlid+"_select",parameters);
		setJson(result);
	}
	
	/**
	 * 公用查询 返回单条数据
	 */

	public void commonQueryOneData() throws Exception {
		HashMap<String, Object> parameters = (HashMap<String, Object>) this.getParams();
		handlerPar(parameters);
		String sqlid = getPara("sqlid");
		if (sqlid==null) {
			throw new RapidException("未设置sqlid！");
		}
		HashMap<String, Object> result = CommonDao.selectOneByXml(sqlid+"_selectOneData",parameters);
		setJson(result);
	}	
	
	/**
	 * 公用新增
	 */
	public void commonInsert() throws Exception{
		HashMap<String, Object> parameters = (HashMap<String, Object>) this.getParams();
		handlerPar(parameters);
		checkDATA(parameters);
		String sqlid = getPara("sqlid");
		if (sqlid==null) {
			throw new RapidException("未设置sqlid！");
		}
		int parimaryKey = CommonDao.insertByXml(sqlid+"_insert",parameters);
		setJson(parimaryKey);
	}
	
	/**
	 * 公用修改
	 */
	public void commonUpdate() throws Exception {
		HashMap<String, Object> parameters = (HashMap<String, Object>) this.getParams();
		handlerPar(parameters);
		checkDATA(parameters);
		String sqlid = getPara("sqlid");
		if (sqlid==null) {
			throw new RapidException("未设置sqlid！");
		}
		CommonDao.updateByXml(sqlid+"_update",parameters);
	}
	
	/**
	 * 公用删除
	 */
	public void commonDelete() throws Exception{
		HashMap<String, Object> parameters = (HashMap<String, Object>) this.getParams();
		handlerPar(parameters);
		checkDATA(parameters);
		String sqlid = getPara("sqlid");
		if (sqlid==null) {
			throw new RapidException("未设置sqlid！");
		}
		CommonDao.deleteByXml(sqlid+"_delete",parameters);
	}
	
	/**
	 * 数据判断
	 * @param parameters
	 * @throws Exception
	 */
	private void checkDATA(HashMap<String, Object> parameters) throws Exception{
		String checkdatas = (String) parameters.get("check_data");
		if (checkdatas!=null&&!checkdatas.equals("")) {
			String[] arrCHECKDATAS = checkdatas.split(",");
			for (int i = 0; i < arrCHECKDATAS.length; i++) {
				HashMap<String, Object> unqResult =  CommonDao.selectOneByXml(arrCHECKDATAS[i]+"_checkdata", parameters);
				Object flag = 0;
				String message = null;
				if (RapidConsts.getCURRENT_DB_TYPE()==RapidConsts.DB_TYPE_ORACLE) {
					flag = unqResult.get("FLAG");
					message = (String) unqResult.get("MESSAGE");
				}else {
					flag = unqResult.get("flag");
					message = (String) unqResult.get("message");
				}
				if (Integer.parseInt(flag.toString())>0) {
					throw new RapidException(message);
				}
			}
		}		
	}
	
	/**
	 * 导出excel
	 * @throws Exception
	 */
	public void exportExcel() throws Exception{
		HashMap<String, Object> parameters = (HashMap<String, Object>) this.getParams();
		handlerPar(parameters);
		int page = getParaToInt("page");
		int limit = getParaToInt("limit");
		String type = getPara("type");
		String dataIndexes = getPara("dataIndexes");
		String columnNames = getPara("columnNames");
		String sqlid = getPara("sqlid");
		if (sqlid==null) {
			throw new RapidException("未设置sqlid！");
		}
		if ("all".equals(type)) {
			page = 1;
			limit = 999999999;
			parameters.put("page", page);
			parameters.put("limit", limit);
		}
		Page<HashMap<String, Object>> result=null;
		String excelPath = null;
		if ("gasctj".equals(sqlid)) {
			String gxdwbm = (String) parameters.get("gxdwbm");
			if (null==gxdwbm||"".equals(gxdwbm)) {
				CurrentRyxx currentRyxx = getCurrentRyxx();
				parameters.put("gxdwbm", currentRyxx.getOrgid());
			}
			List<HashMap<String, Object>> list = RapidDao.selectListByXml("gasctj_select", parameters);
			excelPath = createExcel(sqlid,list, dataIndexes, columnNames);
		}else {
			if ("qrsctj".equals(sqlid)) {
				String tjrq = (String) parameters.get("tjrq");
				String[] dates = DateUtil.getBeforeDates(tjrq, 7);
				for(int i=7;i>=1;i--){
					parameters.put("tjrq_"+i, dates[i-1]);
				}
				//绑定当前登录人信息
				bindCurrentRyxxToMap(parameters);
			}
			result = CommonDao.paginateForExcelByXml(page,limit,"Dynasearch_"+sqlid+"_count", "Dynasearch_"+sqlid+"_getData", parameters);
			excelPath = createExcel(sqlid,result.getList(), dataIndexes, columnNames);
		}
		setJson(excelPath);
	}	
	
	/**
	 * 创建excel
	 * @param datas
	 * @param dataIndexes
	 * @param columnNames
	 * @return
	 */
	protected String createExcel(String sqlid,List<HashMap<String, Object>> datas,String dataIndexes,String columnNames){
		String excelPath = getSession().getServletContext().getRealPath("/")+"/tmp/";
		String excelName = UUID.randomUUID().toString();
		String[] arrDataIndex = dataIndexes.split(",");
		String[] arrColumnName = columnNames.split(",");
		String value = null;
		try {
			WritableWorkbook book = Workbook.createWorkbook(new File(excelPath+excelName+".xls")); 
			WritableSheet sheet = book.createSheet("第一页", 0);
			HashMap<String, Object> data = null;
			Object dataValue = null;
			for(int i=0;i<datas.size();i++){
				data = datas.get(i);
				for(int j=0;j<arrDataIndex.length;j++){
					dataValue = data.get(arrDataIndex[j]);
					if (dataValue==null) {
						dataValue = "";
					}
					//写入数据
					sheet.setColumnView(j, 25);
					if (i==0) {
						sheet.addCell(new Label(j,i,arrColumnName[j],getHeaderCellStyle()));
					}
					value = rendererCellData(sqlid,arrDataIndex[j],dataValue.toString());
					value = value ==null?dataValue.toString():value;
					sheet.addCell(new Label(j,i+1,value,getBodyCellStyle()));
				}
			}
			book.write();
			book.close();
		} catch (Exception e) {
			throw new RapidException(e.getMessage());
		}
		return excelName;
	}

	/**
	 * 表头样式
	 * @return
	 */
	private WritableCellFormat getHeaderCellStyle(){  
		WritableFont font = new WritableFont(WritableFont.createFont("宋体"),  
                                             10,   
                                             WritableFont.BOLD,   
                                             false,  
                                             UnderlineStyle.NO_UNDERLINE);  
        WritableCellFormat headerFormat = new WritableCellFormat(NumberFormats.TEXT);  
        try {  
        	//添加字体设置  
            headerFormat.setFont(font);  
            //设置单元格背景色：表头为黄色  
            headerFormat.setBackground(Colour.GRAY_25);  
            //整个表格线为细线、黑色  
            headerFormat.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK); 
            //表头内容水平居中显示  
            headerFormat.setAlignment(Alignment.CENTRE);      
        } catch (WriteException e) {  
            System.out.println("表头单元格样式设置失败！");  
        }  
        return headerFormat;  
    }
	
	/**
	 * 表体样式
	 * @return
	 */
	private WritableCellFormat getBodyCellStyle(){  
		WritableFont font = new WritableFont(WritableFont.createFont("宋体"),  
                                             10,   
                                             WritableFont.NO_BOLD,   
                                             false,  
                                             UnderlineStyle.NO_UNDERLINE);  
        WritableCellFormat bodyFormat = new WritableCellFormat(font);  
        try {  
        	//设置单元格背景色：表体为白色  
            bodyFormat.setBackground(Colour.WHITE);  
            //整个表格线为细线、黑色  
            bodyFormat.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);  
        } catch (WriteException e) {  
            System.out.println("表体单元格样式设置失败！");  
        }  
        return bodyFormat;  
    }  	
	   
	/**
	 * 文件下载
	 */
	public void downLoadFile(){
	   String excelPath = getSession().getServletContext().getRealPath("/")+"/tmp/";
	   HttpServletResponse response = getResponse();
	   String tartgetName = getPara("targetName");
	   String excelName = getPara("excelName");
	   File file = null;
	   try{
		   file = new File(excelPath+tartgetName+".xls");
		   String fileName=file.getName();
		   InputStream is=new FileInputStream(file);
		   OutputStream os=response.getOutputStream();
		   BufferedInputStream bis = new BufferedInputStream(is);
		   BufferedOutputStream bos = new BufferedOutputStream(os);
		   excelName = java.net.URLEncoder.encode(excelName, "UTF-8");// 处理中文文件名的问题
		   excelName = new String(excelName.getBytes("UTF-8"), "GBK");// 处理中文文件名的问题
		   response.reset();
		   response.setContentType("application/x-msdownload");// 不同类型的文件对应不同的MIME类型
		   if(excelName==null||"".equals(excelName))
		   {
			   response.setHeader("Content-Disposition", "attachment; filename="+fileName);
		   }else{
			   excelName = excelName+".xls";
			   response.setHeader("Content-Disposition", "attachment; filename="+excelName);
		   }
		   int bytesRead = 0;
		   byte[] buffer = new byte[1024];
		   while ((bytesRead = bis.read(buffer)) != -1){
		   bos.write(buffer, 0, bytesRead);// 将文件发送到客户端
		}
		bos.flush();
		bos.close();
		bis.close();
		is.close();
		os.close();
		bos=null;
		bis=null;
		is=null;
		os=null;  
		}catch(Exception e){
			throw new RapidException(e.getMessage());
		}finally{
			 file.delete();
		}
   }	   
	
}
